package logic

import (
	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/Servers/UserAction/userAction"
	"MyBlogv2/blog-common/HttpCode"
	helper "MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *UserAction.LoginRequest) (*UserAction.LoginResponse, error) {
	username := in.Username
	password := in.Password
	loginIp := in.LoginIp
	var user models.User
	err := models.Db.Model(new(models.User)).Where("username = ?", username).First(&user).Error
	if err != nil {
		return &UserAction.LoginResponse{
			Code: int64(HttpCode.USERNAME_OR_PASSWORD_ERROR),
		}, nil
	}
	if !helper.AnalysisBcryptPassword(user.Password, password) {
		return &UserAction.LoginResponse{
			Code: int64(HttpCode.USERNAME_OR_PASSWORD_ERROR),
		}, nil
	}
	token, err := helper.GenerateToken(user.Id)
	if err != nil {
		return &UserAction.LoginResponse{
			Code: int64(HttpCode.FAILURE),
		}, nil
	}
	models.Db.Model(new(models.User)).Where("id = ?", user.Id).Update("login_ip", loginIp)
	models.Db.Model(new(models.User)).Where("id = ?", user.Id).Update("login_time", models.MyTime(time.Now()))
	return &UserAction.LoginResponse{
		Code:  int64(HttpCode.SUCCESS),
		Token: token,
	}, nil
}
